import router from 'umi/router';

import { accountLogin, accountLogout, sendCaptcha,resetPassword,editPassword, loginFingerprintCheck, bindEmailSendCode, bindEmailCheck, loginForceModifypwd } from '@/services/login';
import { getMenuData } from '@/services/menu';
import { putToken, sessionClear } from '@/utils/utils';
import { notification } from 'antd';

const loginModel = {
  namespace: 'login',
  state: {
    response: {},
    updatePasswordModal: false,
    bindEmailOpen: false,
    validatorEmailOpen: false,
    msgTip: undefined,
    pwdStrategy: {},
    pwdExpiredDays: -1,
    oldPassword: '',
  },
  effects: {
    *login({ payload, callback }, { call, put }) {
      const { pwd, ..._payload } = payload;
      const response = yield call(accountLogin, { ..._payload});
      callback(response)
      if(response.statusCode === "0"){
        yield put({
          type: 'save',
          payload: { response },
        });
        if (response.data && response.data.token) {
          // 登录成功之后校验密码策略通过后跳转到主页,否则弹出密码修改
          const menuDataRes = yield call(getMenuData, {
            headers: {
              OptAuthorization: `${response.data.token}`
            },
          });
          const regular = menuDataRes?.data?.pwdStrategy ?? {};
          yield put({
            type: 'save',
            payload: {
              pwdStrategy: regular,
              tempToken: response.data.token,
              pwdExpiredDays: response.data.passwordRemainingValidity,
              oldPassword: pwd,
            },
          });
          let pwdExpiredDays = Number(response.data.passwordRemainingValidity);
          if(!isNaN(pwdExpiredDays) && pwdExpiredDays > 0 && pwdExpiredDays <= 5) {
            notification.warning({
              message: '密码到期提示',
              description:`您的密码还有${pwdExpiredDays}天过期失效，请及时修改密码！`,
              duration: 0,
            });
          }
          sessionStorage.setItem('pwdValidityPeriod', `${pwdExpiredDays}`)
          putToken(response.data.token);
          router.push('/');
          // if (regular.pwdStrategy && !new RegExp(regular.pwdStrategy).test(pwd)) {
          //   yield put({
          //     type: 'save',
          //     payload: {
          //       updatePasswordModal: true,
          //       pwdStrategy: regular,
          //       tempToken: response.data.token,
          //       oldPassword: pwd,
          //     },
          //   });
          // } else if (regular.pwdStrategy && new RegExp(regular.pwdStrategy).test(pwd)) {
          //   putToken(response.data.token);
          //   router.push('/');
          // }
        }
      }else {
        let { statusCode, statusMessage } = response;
        let statusCodePayload: any = {
          9043: { bindEmailOpen: true },
          9049: { updatePasswordModal: true, oldPassword: pwd },
          9046: { updatePasswordModal: true, oldPassword: pwd  },
          9047: { validatorEmailOpen: true },
          9048: { validatorEmailOpen: true },
          9050: { updatePasswordModal: true, oldPassword: pwd },
        }
        yield put({
          type: 'save',
          payload: {
            ...(statusCodePayload[statusCode] || {}),
            msgTip: statusMessage
          }
        });
      }
    },
    // 登录校验邮箱，指纹
    *fingerprintCheck({ payload, callback }, { call, put }) {
      const response = yield call(loginFingerprintCheck, { ...payload });
      callback?.(response)
    },
    *sendEmailCode({ payload, callback }, { call, put }) {
      const response = yield call(bindEmailSendCode, payload);
      callback?.(response);
      return Promise.resolve(response)
    },
    *checkEmailCode({ payload, callback }, { call, put }) {
      const response = yield call(bindEmailCheck, payload);
      callback?.(response)
    },
    *logout( _, { call }) {
      const response = yield call(accountLogout);
      if(response.statusCode === "0"){
        // 退出登录接口返回成功，清除session并跳转跳转到登录页
        sessionClear();
        router.replace( '/user/login');

        //清除引入js并强制刷新
      let callScript = document.querySelector("script[data-callType='callScript']")
      console.log('callll', callScript);
      if(callScript){
      document.body.removeChild(callScript);
      window.location.reload();
      }
      }
    },
    // 登录校验，修改密码
    *loginForceModifypwd({ payload, callback }, { call, put }) {
      const response = yield call(loginForceModifypwd, payload);
      yield put({ type: 'save', payload: { response }});
      callback(response);
    },
    *sendCaptcha({ payload, callback }, { call, put }) {
      const response = yield call(sendCaptcha, payload);
      yield put({ type: 'save', payload: { response }});
      callback(response)
    },
    *resetPassword({ payload, callback }, { call, put }) {
      const response = yield call(resetPassword, payload);
      if(response.statusCode === "0"){
        yield put({ type: 'save', payload: { response }});
        callback(response)
      }
    },
    *editPassword({ payload, callback }, { call, put, select }) {
      const tempToken = yield select(state => state.login.tempToken)
      if(tempToken) {
        payload.headers = {
          OptAuthorization: `${tempToken}`,
        }
      }
      const response = yield call(editPassword, payload);
      if(response.statusCode === "0"){
        yield put({ type: 'save', payload: { response, tempToken: '',  updatePasswordModal: false, oldPassword: ''}});
        callback(response)
      }
    },
  },
  reducers: {
    save(state,action) {
      return {
        ...state,
        ...action.payload,
      };
    }
  },
};
export default loginModel;
